package jay.home.bet.job;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimerTask;

import jay.home.bet.domain.Comp;
import jay.home.bet.domain.Daxiao;
import jay.home.bet.domain.Event;
import jay.home.bet.domain.League;
import jay.home.bet.domain.Rangqiu;
import jay.home.bet.domain.Team;
import jay.home.bet.domain.logic.BasicService;
import jay.home.bet.domain.logic.OddsService;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.spowin.Mansion88.MansionGQ;
import com.spowin.Mansion88.Util;

public class GunQiuBot extends TimerTask
{
	protected final Log logger = LogFactory.getLog(getClass());
	private OddsService oddsService;
	private BasicService basicService;
	
	static final String LOGON_SITE = "www.mansion88.com";
	static final int LOGON_PORT = 80;
	static HttpClient hc = new HttpClient();
	
	static//登陆明升网站, 一般情况下不需要登陆.
	{
		hc.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT, "http");
		hc.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
		HttpMethod get = new GetMethod();

		try{
			hc.executeMethod(get);
		} catch (HttpException e){
			e.printStackTrace();
		} catch (IOException e){
			e.printStackTrace();
		}
		get.releaseConnection();
	}

	public void run()
	{
		HttpMethod gunqiu = new GetMethod("/OddsDisplay/MemberOdds/rbdata.asp?sport=0&hdpver=2&ViewType=RB");
		try
		{
			hc.executeMethod(gunqiu);
			BufferedReader br = new BufferedReader(new InputStreamReader(gunqiu.getResponseBodyAsStream()));
			String nn = "";
			List<String> value = new ArrayList<String>();
			while ((nn = br.readLine())!=null)//读取数据数组的行, 这些行形式如:_a[2] = ['','FRA','FRANCE LIGUE 1','200721710','-120','02/04','3:00AM','True','Lens (H)','Paris Saint Germain','0.5','0.5','1.050','0.850','2.25','2/2.5','1.060','0.840','1.90','3.80','3.00','200722004','True','0.25','0/0.5','0.750','1.175','2','2','0.830','1.075','0.25','0/0.5','1.200','0.710','0.75','0.5/1','0.850','1.050','2.55','4.00','1.95'];
				if(nn.contains("_a["))value.add(nn);
			
			List<MansionGQ> gunqius = new ArrayList<MansionGQ>();
			for(String item : value)
				gunqius.add(Util.getMansionGQ(item));
			
			gunqiu.releaseConnection();//释放连接
			process(gunqius);
		} catch (Exception e)
		{
			logger.fatal("接水时出现错误, 错误信息:" + e);
			e.printStackTrace();
		}
	}

	private Map<String, MansionGQ> odds = new HashMap<String, MansionGQ>();
	private void process(List<MansionGQ> gunqius)
	{
		Map<String, Integer> counter = new HashMap<String , Integer>();
		for(MansionGQ item : gunqius)
		{
			String id = item.getId();
			logger.debug("获得并预处理赛事 ---> id=" + id + "  主队名=" + item.getHomeName() + "  客队名=" + item.getRoadName());
			if (counter.get(id) == null)counter.put(id, 0);
			else counter.put(id, counter.get(id) + 1);
			item.setId(id + "_" + counter.get(id));
			item.setRoadName(trim(item.getRoadName()));
			item.setHomeName(trim(item.getHomeName()));
			item.setLeagueName(trim2(item.getLeagueName()));
		}
		for(MansionGQ item : gunqius)
		{
			String id = item.getId();
			MansionGQ m = odds.get(id);
			if(m == null)
			{
				odds.put(id, item);
				store(item);
				continue;
			}
			if(!noChange(item, odds.get(id)))
			{
				odds.put(id, item);
				update(item);
				continue;
			}
		}
	}
	
	private void update(MansionGQ item)
	{
		Event event = oddsService.getEvent(item.getId());
		if(event == null)
		{
			logger.warn("bot需要更新赛事, 但是数据库中无此赛事:" + item.getId());
			return;
		}
//		半全场大小数据
		event.getDaxiao().setHome(jay.home.bet.misc.Util.toDouble(item.getDxHome()));
		event.getDaxiao().setRoad(jay.home.bet.misc.Util.toDouble(item.getDxRoad()));
		event.getDaxiao().setPankou(item.getDxPankou());
		event.getDaxiaoHalf().setHome(jay.home.bet.misc.Util.toDouble(item.getDxHomeHalf()));
		event.getDaxiaoHalf().setRoad(jay.home.bet.misc.Util.toDouble(item.getDxRoadHalf()));
		event.getDaxiaoHalf().setPankou(item.getDxPankouHalf());
		
		//半全场让球数据
		event.getRangqiu().setHome(jay.home.bet.misc.Util.toDouble(item.getRqHome()));
		event.getRangqiu().setRoad(jay.home.bet.misc.Util.toDouble(item.getRqRoad()));
		event.getRangqiu().setPankou(item.getRqPankou());
		event.getRangqiu().setWho2who("true".equalsIgnoreCase(item.getRqFlag())?"主让客":"客让主");
		event.getRangqiuHalf().setHome(jay.home.bet.misc.Util.toDouble(item.getRqHomeHalf()));
		event.getRangqiuHalf().setRoad(jay.home.bet.misc.Util.toDouble(item.getRqRoadHalf()));
		event.getRangqiuHalf().setPankou(item.getRqPankouHalf());
		event.getRangqiuHalf().setWho2who("true".equalsIgnoreCase(item.getRqFlagHalf())?"主让客":"客让主");

		event.getComp().setNowResult(item.getCurrentScore());
		
//		更新数据到数据库
		oddsService.updateEvent(event);
	}

	private boolean noChange(MansionGQ item, MansionGQ md)
	{
		if(!item.getCurrentScore().equals(md.getCurrentScore()))return false;
		if(!item.getDxHome().equals(md.getDxHome()))return false;
		if(!item.getDxHomeHalf().equals(md.getDxHomeHalf()))return false;
		if(!item.getDxRoad().equals(md.getDxRoad()))return false;
		if(!item.getDxRoadHalf().equals(md.getDxRoadHalf()))return false;
		if(!item.getDxPankou().equals(md.getDxPankou()))return false;
		if(!item.getDxPankouHalf().equals(md.getDxPankouHalf()))return false;
		if(!item.getRqHome().equals(md.getRqHome()))return false;
		if(!item.getRqHomeHalf().equals(md.getRqHomeHalf()))return false;
		if(!item.getRqRoad().equals(md.getRqRoad()))return false;
		if(!item.getRqRoadHalf().equals(md.getRqRoadHalf()))return false;
		if(!item.getRqPankou().equals(md.getRqPankou()))return false;
		if(!item.getRqPankouHalf().equals(md.getRqPankouHalf()))return false;
		if(!item.getRqFlag().equals(md.getRqFlag()))return false;
		if(!item.getRqFlagHalf().equals(md.getRqFlagHalf()))return false;
		
		return true;
	}

	private void store(MansionGQ item)
	{
		if(oddsService.getEvent(item.getId()) != null)return;
		Event event = new Event();
		Daxiao dx = event.getDaxiao();
		Daxiao dxhalf = event.getDaxiaoHalf();
		Rangqiu rq = event.getRangqiu();
		Rangqiu rqhalf = event.getRangqiuHalf();
		
		event.setType("滚球");
		event.setAcceptBot(true);
		event.setAlive(true);
		event.setFrozen(false);
		event.setPublished(false);
		event.setId(item.getId());
		
		dx.setHome(jay.home.bet.misc.Util.toDouble(item.getDxHome()));
		dx.setRoad(jay.home.bet.misc.Util.toDouble(item.getDxRoad()));
		dx.setPankou(item.getDxPankou());
		dxhalf.setHome(jay.home.bet.misc.Util.toDouble(item.getDxHomeHalf()));
		dxhalf.setRoad(jay.home.bet.misc.Util.toDouble(item.getDxRoadHalf()));
		dxhalf.setPankou(item.getDxPankouHalf());
		
		rq.setHome(jay.home.bet.misc.Util.toDouble(item.getRqHome()));
		rq.setRoad(jay.home.bet.misc.Util.toDouble(item.getRqRoad()));
		rq.setPankou(item.getRqPankou());
		rq.setWho2who("true".equalsIgnoreCase(item.getRqFlag())?"主让客":"客让主");
		rqhalf.setHome(jay.home.bet.misc.Util.toDouble(item.getRqHomeHalf()));
		rqhalf.setRoad(jay.home.bet.misc.Util.toDouble(item.getRqRoadHalf()));
		rqhalf.setPankou(item.getRqPankouHalf());
		rqhalf.setWho2who("true".equalsIgnoreCase(item.getRqFlag())?"主让客":"客让主");
		
		League league = basicService.getLeague(item.getLeagueName());
		if(league == null)league = storeLeague(item.getLeagueName());
		Team home = basicService.getTeam(item.getHomeName()); 
		if(home == null)home = storeTeam(item.getHomeName(), league.getId());
		Team road = basicService.getTeam(item.getRoadName());
		if(road == null)road = storeTeam(item.getRoadName(), league.getId());
		Comp comp = basicService.getCompByDetail(home.getId(), road.getId(), item.getDatetime());
		if(comp == null)comp = storeComp(home, road, league, item.getDatetime());
		
		event.setComp(comp);
		event.setDaxiao(dx);
		event.setDaxiaoHalf(dxhalf);
		event.setRangqiu(rq);
		event.setRangqiuHalf(rqhalf);
		
		oddsService.insertEvent(event);
	}

	private Comp storeComp(Team home, Team road, League league, String datetime)
	{
		Comp comp = new Comp();
		comp.setId(jay.home.bet.misc.Util.uuid());
		comp.setHome(home);
		comp.setRoad(road);
		comp.setLeague(league);
		comp.setTime(jay.home.bet.misc.Util.string2Date(datetime));
		comp.setAlive(true);
		logger.info("bot检测到新赛事(id=" + comp.getId() +"), 自动保存到数据库中.....");
		basicService.insertComp(comp);
		return basicService.getComp(comp.getId());
	}

	private Team storeTeam(String t, String league)
	{
		Team team = new Team();
		team.setId(t);
		team.setName_en(t);
		team.setName_tw(t);
		team.setName_zh(t);
		team.setLeagueid(league);
		logger.info("bot检测到新球队(id=" + team.getId() +"), 自动保存到数据库中.....");
		basicService.insertTeam(team);
		return basicService.getTeam(t);
	}

	private League storeLeague(String l)
	{
		League league = new League();
		league.setId(l);
		league.setName_en(l);
		league.setName_tw(l);
		league.setName_zh(l);
		basicService.insertLeague(league);
		return basicService.getLeague(league.getId());
	}

	/**如果en为 "Southampton (H)", 则去掉"(H)", 并去掉首尾字符*/
	private String trim(String target)
	{
		return target.split("\\(.+")[0].trim();
	}
	
	private String trim2(String league)
	{
		if(league.contains("(") && league.contains(")"))
			return league.substring(league.indexOf("(") + 1, league.indexOf(")"));
		return league;
	}
	

	public BasicService getBasicService()
	{
		return basicService;
	}
	public void setBasicService(BasicService basicService)
	{
		this.basicService = basicService;
	}

	public OddsService getOddsService()
	{
		return oddsService;
	}

	public void setOddsService(OddsService oddsService)
	{
		this.oddsService = oddsService;
	}
}
